<?php
require_once "../config/database.php";
class DbController extends AppController
{
    public $name       = "Db";
    public $uses       = array('Dbbackup');
    public $components = array('Sql');


    public function dbbackupmgnt()
    {
        $this->theme = "admin";
        $flag = $this->data['flag'];
        $msg = null;

        switch ($flag) {
            case "search":
                $search_str = $this->data['search']['subject'];
                self::set('search_str', $search_str);
                break;

            case "backup";
                $db = new DATABASE_CONFIG();
                $filename = "{$db->default['database']}-".date('Ymd').".sql";
                $dump_result = $this->Sql->create_dump($filename);

                if ($dump_result === false) {
                    $msg = "Error on creating dump file";
                } else {
                    $value['dumpfile'] = $filename;
                    $value['location'] = APP . "db" . DS;
                    $value['date_added'] = date('Y-m-d H:i:s');
                    $save_result = $this->Dbbackup->_save($value);
                    if (!is_numeric($save_result)) {
                        $msg = print_r($save_result, true);
                    } else {
                        $msg = "database has been backup using {$filename}";
                    }

                    // clear flag value
                    unset($this->data['flag']);
                }
                break;

            case "delete":
                if ($this->data['row']['id']) {
                    foreach ($this->data['row']['id'] as $v) {
                        $info = $this->Dbbackup->get($v, "first");
                        $update_result = $this->Dbbackup->_save(array('deleted' => 1), $v);
                        if (!is_numeric($update_result)) {
                            $msg = "Error deleting selected dump file(s)";
                            break;
                        }

                        unlink("{$info['Dbbackup']['location']}{$info['Dbbackup']['dumpfile']}");
                        unset($info);
                    }
                }
                break;
        }

        if (isset($search_str)) {
            $this->paginate['conditions'][] = array('dumpfile LIKE' => "%{$this->data['search']['subject']}%", 'deleted' => 0);
        } else {
            $this->paginate['conditions'][] = array('deleted' => 0);
        }

        $limit = isset($this->data['limit'])?$this->data['limit']:20;
        $this->paginate['limit'] = $limit;
        $this->paginate['order'] = array('dumpfile' => 'ASC');
        $data = $this->paginate('Dbbackup');


        self::set('limit', $limit);
        self::set('data', $data);
        self::set('count', count($data));
        self::set('msg', $msg);
    }
}
?>
